package pers.cyril.jdb.common.util;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import pers.cyril.jdb.common.annotation.ConfigName;

import java.lang.reflect.Field;
import java.util.NoSuchElementException;

/**
 * 说点什么吧
 *
 * @author Wang Cyril
 * @date 2024/5/24 20:56
 */
public class PropertiesParseUtils {

    public static <T> T bindProperties2Object(String path, T obj) throws ConfigurationException, IllegalAccessException {
        Configuration config = new PropertiesConfiguration(path);
        Class<?> objClass = obj.getClass();
        Field[] declaredFields = objClass.getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            if (!field.isAnnotationPresent(ConfigName.class)) {
                continue;
            }
            ConfigName configName = field.getAnnotation(ConfigName.class);
            Class<?> fieldType = field.getType();
            Object value = null;
            if (fieldType == String.class) {
                value = config.getString(configName.value(), null);
            } else if (fieldType == Integer.class) {
                value = config.getInteger(configName.value(), null);
            } else if (fieldType == Float.class) {
                value = config.getFloat(configName.value(), null);
            } else {
                throw new IllegalArgumentException(String.format("unsupport field type %s", fieldType.getName()));
            }

            if (value == null && configName.required()) {
                throw new NoSuchElementException(String.format("required property [%s] can not found from config file", configName.value()));
            }

            if (value != null) {
                field.set(obj, value);
            }

        }

        return obj;

    }
}
